<template>
  <el-dialog
    title="视频播放"
    :model-value="showVideoPlayer"
    @update:model-value="(value) => emit('update:showVideoPlayer', value)"
    width="900px"
    :before-close="handleClose"
    append-to-body
  >
    <div class="video-player-container">
      <!-- H265播放器 -->
      <div class="player-section">
        <div v-if="!wsUrl" class="loading-placeholder">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在获取视频流...</p>
        </div>
        <H265web 
          v-else
          ref="h265webRef" 
          :videoUrl="wsUrl" 
          :error="videoError" 
          height="500px"
          :hasAudio="hasAudio"
        />
      </div>
      
      <!-- 摄像头信息 -->
      <div class="camera-info-section">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">摄像头名称</span>
            <span class="value">{{ selectedCamera?.name || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备位置</span>
            <span class="value">{{ selectedCamera?.location || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备状态</span>
            <el-tag :type="selectedCamera?.status === 'online' ? 'success' : 'danger'">
              {{ selectedCamera?.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">设备ID</span>
            <span class="value">{{ selectedCamera?.wvp_device_id || '未配置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">通道ID</span>
            <span class="value">{{ selectedCamera?.wvp_channel_id || '未配置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">流地址</span>
            <span class="value stream-url" :title="wsUrl">{{ wsUrl || '获取中...' }}</span>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick, computed } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import H265web from "@/components/H265web/index.vue"

// 定义props
const props = defineProps({
  showVideoPlayer: Boolean,
  selectedCamera: Object,
  streamInfo: Object
})

// 定义事件
const emit = defineEmits(['close', 'update:showVideoPlayer'])

// 播放器状态
const hasAudio = ref(false)

// 模板引用
const h265webRef = ref(null)

// 流地址
const wsUrl = ref('')

// 计算当前播放器引用
const cusPlayerRef = computed(() => {
  return h265webRef.value
})

// 暴露ref给父组件
defineExpose({
  cusPlayerRef: cusPlayerRef
})

// 视频错误处理
const videoError = (e) => {
  console.log("H265播放器错误：" + JSON.stringify(e))
}

// 关闭对话框
const handleClose = () => {
  emit('update:showVideoPlayer', false)
  emit('close')
}

// 监听selectedCamera变化，但不直接使用RTSP URL，等待streamInfo
watch(() => props.selectedCamera, (camera) => {
  console.log('📺 VideoPlayerModal selectedCamera 变化:', camera)
  
  if (camera) {
    console.log('📡 VideoPlayerModal 等待streamInfo提供播放地址...')
    // 不直接使用camera.rtsp_url，等待useVideoPlayer处理后的streamInfo
  } else {
    wsUrl.value = ''
    console.log('⚠️ VideoPlayerModal 无摄像头信息')
  }
}, { immediate: true })

// 监听streamInfo变化，使用处理后的播放地址
watch(() => props.streamInfo, (newStreamInfo) => {
  console.log('📺 VideoPlayerModal streamInfo 变化:', newStreamInfo)
  
  if (newStreamInfo) {
    // 优先选择适合H265播放器的流地址格式
    // 优先级：ws_flv > flv > hls > rtsp > 其他
    const preferredUrlFields = ['ws_flv', 'flv', 'hls', 'rtsp', 'url', 'playUrl', 'streamUrl']
    let foundUrl = null
    
    for (const field of preferredUrlFields) {
      if (newStreamInfo[field]) {
        foundUrl = newStreamInfo[field]
        console.log(`📡 VideoPlayerModal 选择播放地址字段 ${field}:`, foundUrl)
        break
      }
    }
    
    if (foundUrl) {
      wsUrl.value = foundUrl
      console.log('✅ VideoPlayerModal 播放地址已设置:', wsUrl.value)
    } else {
      console.log('❌ VideoPlayerModal 未找到任何播放地址字段')
      console.log('可用字段:', Object.keys(newStreamInfo))
    }
  }
}, { immediate: true })

// 获取摄像头流信息的辅助函数
const getCameraStreamInfo = async (cameraId) => {
  try {
    const response = await fetch(`/api/v1/cameras/${cameraId}/stream-info`)
    const data = await response.json()
    
    if (data.success && data.data && data.data.primary_url) {
      wsUrl.value = data.data.primary_url
      console.log('✅ VideoPlayerModal 从stream-info获取播放地址:', wsUrl.value)
    } else {
      console.log('❌ VideoPlayerModal stream-info接口无播放地址')
    }
  } catch (error) {
    console.error('❌ VideoPlayerModal 获取stream-info失败:', error)
  }
}

// 监听对话框关闭，清理播放器
watch(() => props.showVideoPlayer, (newVal) => {
  if (!newVal && h265webRef.value) {
    // 对话框关闭时，停止播放器
    try {
      if (typeof h265webRef.value.destroy === 'function') {
        h265webRef.value.destroy()
      }
    } catch (error) {
      console.warn('停止H265播放器时出错:', error)
    }
  }
  
  if (newVal) {
    nextTick(() => {
      console.log('VideoPlayerModal 显示，H265播放器引用:', cusPlayerRef.value)
    })
  }
})


</script>

<style lang="scss" scoped>
.video-player-container {
  .player-section {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: #000;
    height: 500px;
    
    .loading-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #fff;
      
      .el-icon {
        font-size: 32px;
        margin-bottom: 16px;
      }
      
      p {
        margin: 0;
        font-size: 16px;
      }
    }
    
    :deep(.h265web-container) {
      width: 100%;
      height: 500px;
    }
  }
  
  .camera-info-section {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    
    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      
      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: white;
        border-radius: 6px;
        border: 1px solid #e9ecef;
        
        .label {
          font-weight: 600;
          color: #495057;
          min-width: 80px;
        }
        
        .value {
          color: #6c757d;
          text-align: right;
          flex: 1;
          margin-left: 12px;
          
          &.stream-url {
            font-family: monospace;
            font-size: 12px;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
      
      // 流地址占满整行
      .info-item:last-child {
        grid-column: 1 / -1;
        
        .value {
          max-width: none;
        }
      }
    }
  }
}

// 确保播放器容器样式
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>